package com.lz.comm.net

import android.os.Handler
import android.os.Looper
import androidx.annotation.MainThread
import com.lz.library.BuildConfig
import okhttp3.Interceptor
import okhttp3.Response

/**
 *  author: you : 2020/04/9
 *  http请求处理拦截器
 */
object HttpInterceptor : Interceptor {

    //请求日志处理
    private val logInterceptor = HttpLogInterceptor(BuildConfig.isRelease)

    //token失效处理
    private val tokenInterceptor = HttpTokenInterceptor()

    private val handler = Handler(Looper.getMainLooper())

    var tokenExpiredListener: OnTokenExpiredListener? = null
        @MainThread set

    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val builder = request.newBuilder()
        val logSwitch = logInterceptor.onRequest(request, builder)
        tokenInterceptor.requestToken(builder)
        request = builder.build()
        val startNs = System.nanoTime()
        try {
            val response = chain.proceed(request)
            if (logSwitch) logInterceptor.onResponse(response, startNs)
            if (tokenInterceptor.checkTokenExpired(response)) {
                handler.post { tokenExpiredListener?.onExpired()}
            }
            return response
        } catch (e: Exception) {
            if (logSwitch) logInterceptor.onError(request, e)
            throw e
        }
    }

    @MainThread
    fun setToken(token: String?) = tokenInterceptor.setToken(token)

    interface OnTokenExpiredListener {
        fun onExpired()
    }
}